package com.wu.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wu.mapper.ArticleSearchMapper;
import com.wu.mapper.UsersMapper;
import com.wu.pojo.Articles;
import com.wu.pojo.model.ArticleModel;
import com.wu.pojo.model.UserToken;
import com.wu.pojo.view.ArticleSearch;
import com.wu.service.ArticleSearchService;
import com.wu.util.ArticleConversionUtil;
import com.wu.util.TokenUtils;
import lombok.SneakyThrows;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.wltea.analyzer.lucene.IKAnalyzer;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: 吴磊
 * @program: blog
 * @create: 2021-05-07 11:54
 */
@Service
public class ArticleSearchServiceImpl extends ServiceImpl<ArticleSearchMapper, ArticleSearch> implements ArticleSearchService {

    @Autowired
    private ArticleSearchMapper articleSearchMapper;

    @Autowired
    private ArticleConversionUtil articleConversionUtil;
    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private TokenUtils tokenUtils;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 索引存放路径
     */
    @Value("${lucene.index.path}")
    private String indexPath;

    @Override
    public List<ArticleSearch> getArticleByArticleTitle(String articleTitle) {
        if (StringUtils.isEmpty(articleTitle)) {
            articleTitle = "";
        }
        int len = articleTitle.length();
        StringBuffer sb = new StringBuffer();
        sb.append("%");
        for (int i = 0; i < len; i++) {
            sb.append(articleTitle.charAt(i));
            sb.append("%");
        }
        return articleSearchMapper.getArticleTitle(sb.toString());
    }

    @SneakyThrows
    @Override
    public List<ArticleSearch> getArticleByArticleTitleByLucence(String articleTitle) {
        // 目录对象
        Directory directory = FSDirectory.open(new File(indexPath).toPath());
        // 创建读取工具
        IndexReader reader = DirectoryReader.open(directory);
        // 创建搜索工具
        IndexSearcher searcher = new IndexSearcher(reader);
        QueryParser parser = new QueryParser("articleTitle", new IKAnalyzer());
        Query query = parser.parse(articleTitle);
        // 搜索
        TopDocs topDocs = searcher.search(query, 15);
        long total = topDocs.totalHits.value;
        if (total <= 0) {
            return new ArrayList<>();
        }
        ScoreDoc[] scoreDocs = topDocs.scoreDocs;
        ArrayList<ArticleSearch> res = new ArrayList<>();
        total = total > 15 ? 15 : total;
        for (int i = 0; i < total; i++) {
            ScoreDoc scoreDoc = scoreDocs[i];
            // 获取文档编号
            int docID = scoreDoc.doc;
            Document document = reader.document(docID);
            ArticleSearch articleSearch = new ArticleSearch();
            articleSearch.setArticleId(document.get("articleId"));
            articleSearch.setArticleTitle(document.get("articleTitle"));
            res.add(articleSearch);
        }
        return res;
    }

    @Override
    public HashMap<String, Object> getLikeArticle(String articleTitle, Integer p) {
        if (StringUtils.isEmpty(articleTitle)) {
            articleTitle = "";
        }
        if (p == null || p == 0) {
            p = 1;
        }
        int len = articleTitle.length();
        StringBuffer sb = new StringBuffer();
        sb.append("%");
        for (int i = 0; i < len; i++) {
            sb.append(articleTitle.charAt(i));
            sb.append("%");
        }

        HashMap<String, Object> map2 = new HashMap<>();
        map2.put("like", sb.toString());
        //获取总篇数
        Integer total = articleSearchMapper.getSearchLikeArticleCount(map2);
        int totalPage = (total + 10 - 1) / 10;
        if (totalPage == 0) {
            //总篇数
            map2.put("total", 0);
            //总页数
            map2.put("pages", 0);
            //文章 <=10篇
            map2.put("articles", new ArrayList<>());
            return map2;
        }

        if (p < 1) {
            p = 1;
        }
        if (p > totalPage) {
            p = totalPage;
        }
        map2.put("curPage", (p - 1) * 10);
        HashMap<String, Object> map = new HashMap<>();

        List<Articles> articles = articleSearchMapper.getSearchArticle(map2);

        //处理查出来的文章
        List<ArticleModel> articleModels;
        String isLogin = tokenUtils.parseTokenToken();
        if (StringUtils.isEmpty(isLogin)) {
            //没有登录
            articleModels = articles.stream().map(article -> {
                UserToken userToken = usersMapper.getUserTokenById(article.getUserId());
                ArticleModel articleModel = new ArticleModel();
                BeanUtils.copyProperties(article, articleModel);
                articleModel.setUserToken(userToken);
                map.put(articleModel.getArticleId(), false);
                return articleModel;
            }).collect(Collectors.toList());
        } else {
            //登录了
            UserToken token = tokenUtils.parseTokenToUserToken();
            String loginUserId = token.getUserId();
            articleModels = articles.stream().map(article -> {
                UserToken userToken = usersMapper.getUserTokenById(article.getUserId());
                ArticleModel articleModel = new ArticleModel();
                BeanUtils.copyProperties(article, articleModel);
                articleModel.setUserToken(userToken);
                String articleId = articleModel.getArticleId();
                Boolean isLike = redisTemplate.opsForSet().isMember(loginUserId + "_UP", articleId);
                if (!isLike) {
                    map.put(articleId, false);
                } else {
                    map.put(articleId, true);
                }
                return articleModel;
            }).collect(Collectors.toList());
        }

        //总篇数
        map.put("total", total);
        //总页数
        map.put("pages", totalPage);
        //文章 <=10篇
        map.put("articles", articleModels);
        return map;
    }

    @Override
    public List<ArticleSearch> getArticleByArticleTitle(String articleTitle, String userId) {
        if (StringUtils.isEmpty(articleTitle)) {
            articleTitle = "";
        }
        int len = articleTitle.length();
        StringBuffer sb = new StringBuffer();
        sb.append("%");
        for (int i = 0; i < len; i++) {
            sb.append(articleTitle.charAt(i));
            sb.append("%");
        }
        return articleSearchMapper.getOwnerArticleByUserIdAndArticleTitle(userId, sb.toString());
    }

    @Override
    public HashMap<String, Object> getLikeArticle(String articleTitle, Integer p, String userId) {
        if (StringUtils.isEmpty(articleTitle)) {
            articleTitle = "";
        }
        if (p == null || p == 0) {
            p = 1;
        }
        int len = articleTitle.length();
        StringBuffer sb = new StringBuffer();
        sb.append("%");
        for (int i = 0; i < len; i++) {
            sb.append(articleTitle.charAt(i));
            sb.append("%");
        }

        HashMap<String, Object> map2 = new HashMap<>();
        map2.put("userId", userId);
        map2.put("like", sb.toString());
        //获取总篇数
        Integer total = articleSearchMapper.getSearchLikeArticleCount(map2);
        int totalPage = (total + 10 - 1) / 10;
        if (totalPage == 0) {
            //总篇数
            map2.put("total", 0);
            //总页数
            map2.put("pages", 0);
            //文章 <=10篇
            map2.put("articles", new ArrayList<>());
            return map2;
        }
        if (p < 1) {
            p = 1;
        }
        if (p > totalPage) {
            p = totalPage;
        }
        map2.put("curPage", (p - 1) * 10);
        HashMap<String, Object> map = new HashMap<>();

        List<Articles> articles = articleSearchMapper.getSearchArticle(map2);
        articles = articleConversionUtil.getArticleByOther(articles);
        //处理查出来的文章
        List<ArticleModel> articleModels;
        String isLogin = tokenUtils.parseTokenToken();
        if (StringUtils.isEmpty(isLogin)) {
            //没有登录
            articleModels = articles.stream().map(article -> {
                UserToken userToken = usersMapper.getUserTokenById(article.getUserId());
                ArticleModel articleModel = new ArticleModel();
                BeanUtils.copyProperties(article, articleModel);
                articleModel.setUserToken(userToken);
                map.put(articleModel.getArticleId(), false);
                return articleModel;
            }).collect(Collectors.toList());
        } else {
            //登录了
            UserToken token = tokenUtils.parseTokenToUserToken();
            String loginUserId = token.getUserId();
            articleModels = articles.stream().map(article -> {
                UserToken userToken = usersMapper.getUserTokenById(article.getUserId());
                ArticleModel articleModel = new ArticleModel();
                BeanUtils.copyProperties(article, articleModel);
                articleModel.setUserToken(userToken);
                String articleId = articleModel.getArticleId();
                Boolean isLike = redisTemplate.opsForSet().isMember(loginUserId + "_UP", articleId);
                if (!isLike) {
                    map.put(articleId, false);
                } else {
                    map.put(articleId, true);
                }
                return articleModel;
            }).collect(Collectors.toList());
        }

        //总篇数
        map.put("total", total);
        //总页数
        map.put("pages", totalPage);
        //文章 <=10篇
        map.put("articles", articleModels);
        return map;
    }
}
